package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.topic.Profile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

@Composable
fun Page4(navController: NavController) {
    var userId by remember { mutableStateOf(1L) }
    var userName by remember { mutableStateOf("默认名字") }
    var userBio by remember { mutableStateOf("默认签名") }
    val userAvatar = R.drawable.person

    LaunchedEffect(Unit) {
        val profileData = fetchProfileData(userId)
        profileData?.let {
            userName = it.username
            userBio = it.bio
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp)
                .clickable(onClick = {
                    navController.navigate("profile") { popUpTo("main") { inclusive = false } }
                })
        ) {
            Image(
                painter = painterResource(id = userAvatar),
                contentDescription = "User Profile Picture",
                modifier = Modifier
                    .size(90.dp)
                    .clip(CircleShape)
                    .background(Color.Gray)
            )
            Spacer(modifier = Modifier.width(10.dp))
            Column {
                Text(
                    text = "$userName",
                    fontSize = 20.sp,
                    modifier = Modifier.padding(top = 16.dp)
                )
                Text(
                    text = "$userBio",
                    fontSize = 14.sp,
                    modifier = Modifier.padding(top = 16.dp)
                )
            }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Column {
            ProfileItem(
                iconResId = R.drawable.pay,
                text = "支付",
                onClick = { /* 点击事件 */ }
            )
            ProfileItem(
                iconResId = R.drawable.star,
                text = "收藏",
                onClick = { /* 点击事件 */ }
            )
        }
        Spacer(modifier = Modifier.height(16.dp))
        Column {
            ProfileItem(
                iconResId = R.drawable.settings,
                text = "设置",
                onClick = { navController.navigate("settings") }
            )
            ProfileItem(
                iconResId = R.drawable.help,
                text = "帮助与反馈",
                onClick = { navController.navigate("help") }
            )
            ProfileItem(
                iconResId = R.drawable.about,
                text = "关于",
                onClick = { navController.navigate("about") }
            )
        }
    }
}

private suspend fun fetchProfileData(userId: Long): Profile? {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url("http://192.168.43.10:8080/api/user-profile/$userId")
        .build()

    return withContext(Dispatchers.IO) {
        try {
            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val responseBody = response.body?.string()
                    if (responseBody != null) {
                        val gson = GsonBuilder().create()
                        val jsonObject = gson.fromJson(responseBody, JsonObject::class.java)

                        if (jsonObject.get("success").asBoolean) {
                            val data = jsonObject.getAsJsonObject("data")
                            Profile(
                                userId = data.get("userId")?.asLong ?: 0L,
                                username = data.get("username")?.asString ?: "",
                                bio = data.get("bio")?.asString ?: "",
                                // avatar = "",
                                gender = data.get("gender")?.asString ?: "",
                                height = data.get("height")?.asInt ?: 0,
                                weight = data.get("weight")?.asInt ?: 0,
                                birthday = data.get("birthday")?.asString ?: "",
                                location = data.get("location")?.asString ?: ""
                            )
                        } else {
                            null
                        }
                    } else {
                        null
                    }
                } else {
                    null
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}
